<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
    <head>
        <th:block th:include="include :: header('每日值班')"/>
        <th:block th:include="include :: layout-latest-css"/>
        <th:block th:include="include :: ztree-css"/>
        <th:block th:include="include :: bootstrap-editable-css"/>

        <style>
            .select {
                border: 1px solid #ddd;
                border-radius: 4px;
                background: transparent;
                outline: none;
                height: 30px;
                width: 100px;
            }

            .editable-click, a.editable-click {
                text-decoration: none;
                border-bottom: 0px dashed rgb(0, 136, 204);
                color: #676a6c;
            }

            a.editable-click:hover {
                text-decoration: none;
                /*border-bottom: 1px dashed rgb(0, 136, 204);*/
            }

            .selfDept{
                background-color: #1ab394;
                color: #FFFFFF;
            }

            .selfDept:hover{
                color: #676a6c;
            }

            .currentDay{
                font-weight: 600;
            }
        </style>
    </head>
    <body class="gray-bg">
        <div class="ui-layout-west">
            <div class="box box-main">
                <div class="box-header">
                    <div class="box-title">
                        <i class="fa icon-grid"></i> 组织机构
                    </div>
                    <div class="box-tools pull-right">
                        <a type="button" class="btn btn-box-tool" href="#" onclick="dept()" title="管理部门"><i
                                class="fa fa-edit"></i></a>
                        <button type="button" class="btn btn-box-tool" id="btnExpand" title="展开" style="display:none;">
                            <i class="fa fa-chevron-up"></i></button>
                        <button type="button" class="btn btn-box-tool" id="btnCollapse" title="折叠"><i
                                class="fa fa-chevron-down"></i></button>
                        <button type="button" class="btn btn-box-tool" id="btnRefresh" title="刷新部门"><i
                                class="fa fa-refresh"></i></button>
                    </div>
                </div>
                <div class="ui-layout-content">
                    <div id="tree" class="ztree"></div>
                </div>
            </div>
        </div>

        <div class="ui-layout-center">
            <div class="container-div">
                <div class="row">
                    <div class="col-sm-12 search-collapse">
                        <form id="user-form">
                            <input type="hidden" id="deptId" name="deptId">
                            <input type="hidden" id="parentId" name="parentId">
                            <input type="hidden" id="year" name="year">
                            <input type="hidden" id="month" name="month">
                            <input type="hidden" id="day" name="day">
                            <div class="select-list">
                                <ul>
                                    <li>
                                        姓名：<input type="text" name="userName"/>
                                    </li>

                                    <li class="date" style="display: none">
                                        <label>排班日期： </label>
                                        <input type="text" class="form-control" id="monthPicker" name="date"
                                               placeholder="yyyy-MM">
                                    </li>
                                    <li>
                                        <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i
                                                class="fa fa-search"></i>&nbsp;搜索</a>
                                        <a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i
                                                class="fa fa-refresh"></i>&nbsp;重置</a>

                                    </li>
                                </ul>
                            </div>
                        </form>
                    </div>

                    <div class="btn-group-sm" id="toolbar" role="group">

                        <div class="select-list">
                            <ul>


                                <li class="">

                                    <a class="btn btn-warning" onclick="$.table.exportExcel()"
                                       shiro:hasPermission="system:duty:export">
                                        <i class="fa fa-download"></i> 导出
                                    </a>
                                </li>


                                <li>
                                    <button class="btn btn-primary" onclick="printAllTable()">
                                        <i class="fa fa-print"></i> 打印
                                    </button>
                                    <button class="btn btn-primary" onclick="printMyTable()">
                                        <i class="fa fa-print"></i> 打印我的部门
                                    </button>
                                </li>


                            </ul>

                        </div>
                    </div>

                    <div class="col-sm-12 select-table ">
                        <table id="bootstrap-table"  class="table-bordered"></table>
                    </div>
                </div>
            </div>
        </div>

        <th:block th:include="include :: footer"/>
        <th:block th:include="include :: layout-latest-js"/>
        <th:block th:include="include :: ztree-js"/>
        <th:block th:include="include :: datetimepicker-css"/>
        <th:block th:include="include :: datetimepicker-js"/>
        <th:block th:include="include :: jQuery-print-js"/>
        <script th:inline="javascript">
            var printFlag  = false // 控制打印我的部门标志
            const hospitalName        = [[${@configService.selectConfigByKey("sys.hospital.name")}]]||'韶关市第一人民医院';
            const deptId          = [[${dept.deptId}]];
            const deptName        = [[${dept.deptName}]];
            const editFlag        = [[${@permission.hasPermi('system:duty:edit')}]];
            const removeFlag      = [[${@permission.hasPermi('system:duty:remove')}]];
            const dutyOptionDatas = [[${@dict.getType('biz_duty_type')}]]; // 排班类型下拉框
            const prefix          = ctx + "system/onduty";
            var printDays         = []
            var baseColumns       = ['deptName', 'userName', 'phonenumber']
            var startDate         = 1
            var endDateG          = 31
            var content           = ''
            var deptNameClick     = ''
            let dateStr = ''

            var days            = [
                '星期天',
                '星期一',
                '星期二',
                '星期三',
                '星期四',
                '星期五',
                '星期六'
            ]
            const baseDays            = [
                '星期天',
                '星期一',
                '星期二',
                '星期三',
                '星期四',
                '星期五',
                '星期六',
                '星期天',
                '星期一',
                '星期二',
                '星期三',
                '星期四',
                '星期五',
                '星期六'
            ]
            function renderCurrentDayCSS() {
                var current = new Date().getDate()
                var clazz = '.day'+current

                $(clazz).addClass('currentDay')
                debugger
            }

            function renderCurrentdeptCSS() {
                var deptNameTds = $('#bootstrap-table > tbody   td:nth-child(2)')

                for (let i = 0; i < deptNameTds.length; i++) {
                    var htmlStr = deptNameTds[i]
                    var dep     = $(htmlStr).html().trim()
                    if (dep == deptName) {
                        $(htmlStr).parent().addClass('selfDept')
                    }

                }
            }
            var options           = {
                url: prefix + "/list",
                createUrl: prefix + "/add",
                updateUrl: prefix + "/edit/{id}",
                removeUrl: prefix + "/remove",
                exportUrl: prefix + "/export",
                importUrl: prefix + "/importData",
                importTemplateUrl: prefix + "/importTemplate",
                // sortName: "createTime",
                // sortOrder: "desc",
                pagination:false,
                modalName: "排班",
                showSearch: false,
                showRefresh: true,
                showToggle: false,
                showColumns: false,
                onLoadSuccess: function (data) {
                    var data = $('#bootstrap-table').bootstrapTable('getData', true);
                    //合并单元格

                    mergeCells(data, "deptName", 1, $('#bootstrap-table'));
                    renderCurrentdeptCSS();
                    renderCurrentDayCSS();

                    if (printFlag=='my') {
                        printFlag = '';
                        $('#deptId').val('')
                        printTable();
                    }else if (printFlag == 'print') {
                        printFlag = '';
                        printTable();
                    }
                },
                // onEditableSave: onEditableSave,
            };
            $(function () {
                let panehHidden = false;
                if ($(this).width() < 769) {
                    panehHidden = true;
                }
                $('body').layout({initClosed: panehHidden, west__size: 185});

                initDate()
                queryDeptTree();
                updatePrintDays();
            });

            function updatePrintDays() {
                var val = '0'
                // var selectMonth = $('#monthPicker').val()
                // var year = selectMonth.split('-')[0]
                // var month = selectMonth.split('-')[1]
                let month      = new Date().getMonth() + 1;
                let year       = new Date().getFullYear();
                let endDay     = new Date(year, month, 0).getDate();
                var weekDay    = new Date().getDay()
                var left       = 1 - weekDay % 7
                var right      = 7 - weekDay
                if (weekDay == 0) {
                    left = -6
                    right = 0
                }
                var currentDay = new Date().getDate();
                debugger
                printDays      = [];
                if (+val == 0) {
                    for (let i = left; i <= right; i++) {
                        let day = currentDay + i
                        if(day<=endDay){
                            printDays.push(day)
                        }
                    }

                } else if (+val == 1) {
                    left += 7
                    right += 7

                    for (let i = left; i <= right; i++) {
                        let day = currentDay + i
                        if (day <= endDay) {
                            printDays.push(day);
                        }

                    }
                } else if (+val == 2) { // 上半月
                    for (let i = 1; i <= 15; i++) {
                        printDays.push(i)
                    }
                } else if (+val == 3) { // 下半月
                    for (let i = 16; i <= endDay; i++) {
                        printDays.push(i)
                    }

                } else if (+val == 4) {

                    for (let i = +startDate; i <= endDateG; i++) {
                        printDays.push(i)
                    }
                }

                console.log('---打印日期的范围---')
                console.log(printDays)

                queryUserList()
            }

            function initDate() {
                $("#monthPicker").datetimepicker({
                                                     format: "yyyy-mm-dd",
                                                     startView: 2,
                                                     minView: 3,
                                                     autoclose: true,
                                                 }).on('changeDate', function (event) {
                    event.preventDefault();
                    event.stopPropagation();
                    var year  = event.date.getFullYear()
                    var month = event.date.getMonth() + 1
                    var day = event.date.getDate()
                    month     = month < 10 ? '0' + month : month;
                    $('#year').val(year)
                    $('#month').val(month)
                    $('#day').attr('name',`day${day}`)
                    $('#day').val(day)
                    queryUserList()
                });
                var date = new Date()
                $('#monthPicker').datetimepicker('setDate', date); //把要设置的默认值放入new Date()里面
                var year  = date.getFullYear()
                var day  = date.getDate()
                var month = date.getMonth() + 1
                month     = month < 10 ? '0' + month : month;
                $('#year').val(year)
                $('#month').val(month)
                $('#day').attr('name',`day${day}`)
                $('#day').val(day)
            }
            function getClass(i) {
                return !printDays.includes(i) ? 'noPrint ' +'day'+i : 'day'+i;
            }

            function getWeekColumn(dateStr) {
                let month        = new Date(dateStr).getMonth() + 1;
                let year         = new Date(dateStr).getFullYear();

                let endDay       = new Date(year, month, 0).getDate();
                let startDay     = printDays[0] || 1
                endDay           = printDays[printDays.length - 1]

                const weekColumn = [{class: ' backHalf beforeHalf noPrint'}, {}, {}, {}]

                const dayColumn = [{
                    checkbox: true,
                    class: ' backHalf beforeHalf noPrint'
                }, {
                    field: 'deptName',
                    title: '部门',

                }, {
                    field: 'userName',
                    title: '姓名'
                }, {
                    field: 'phonenumber',
                    title: '电话'
                }]

                const source = dutyOptionDatas.map(d => {
                    let source = {
                        value: d.dictValue,
                        text: d.dictLabel
                    };
                    return source
                })


                for (let i = startDay; i <= endDay; i++) {
                    let week   = baseDays[new Date(year, month-1, i).getDay()]
                    let day    = i > 9 ? i : '0' + i
                    let date   = `${month}月${day}日`
                    let column = {
                        title: week,
                        // align: 'center',
                        colspan: 1,
                        date: date,
                        class: getClass(i)

                    }
                    weekColumn.push(column)
                    dayColumn.push({
                                       field: `day${i}`,
                                       title: date,
                                       class: getClass(i)
                                   })
                }

                return [weekColumn, dayColumn]
            }

            function queryUserList() {
                $.table.destroy();
                options.columns = getWeekColumn(getDateStr())
                $.table.init(options);
            }

            function getDateStr() {
                return $('#year').val() + '-' + $('#month').val()
            }

            // function queryUserList() {
            //     var options = {
            //         url: prefix + "/list",
            //         createUrl: prefix + "/add",
            //         updateUrl: prefix + "/edit/{id}",
            //         removeUrl: prefix + "/remove",
            //         exportUrl: prefix + "/export",
            //         importUrl: prefix + "/importData",
            //         importTemplateUrl: prefix + "/importTemplate",
            //         // sortName: "createTime",
            //         // sortOrder: "desc",
            //         modalName: "每日值班",
            //         showSearch: false,
            //         showRefresh: true,
            //         showToggle: false,
            //         showColumns: false,
            //         pagination: false,
            //         columns: [
            //             {
            //                 field: '-',
            //                 title: '序号',
            //                 formatter: function (value, row, index) {
            //                     return index+1
            //                 }
            //             },
            //             {
            //                 field: 'deptName',
            //                 title: '科室'
            //             },
            //             {
            //                 field: 'userName',
            //                 title: '姓名'
            //             },
            //             {
            //                 field: 'dutyType',
            //                 title: '值班情况'
            //                 // formatter: function (value, row, index) {
            //                 //     return $.table.selectDictLabel(dutyOptionDatas, value);
            //                 // }
            //             },
            //             {
            //                 field: 'loginName',
            //                 title: '登录名'
            //             },
            //             {
            //                 field: 'phonenumber',
            //                 title: '电话'
            //             }
            //
            //            ]
            //
            //     };
            //     $.table.init(options);
            // }

            function queryDeptTree() {
                var url     = ctx + "system/dept/treeData";
                var options = {
                    url: url,
                    expandLevel: 2,
                    onClick: zOnClick
                };
                $.tree.init(options);

                function zOnClick(event, treeId, treeNode) {
                    $("#deptId").val(treeNode.id);
                    $("#parentId").val(treeNode.pId);
                    deptNameClick = treeNode.name
                    $.table.search();
                }
            }

            $('#btnExpand').click(function () {
                $._tree.expandAll(true);
                $(this).hide();
                $('#btnCollapse').show();
            });

            $('#btnCollapse').click(function () {
                $._tree.expandAll(false);
                $(this).hide();
                $('#btnExpand').show();
            });

            $('#btnRefresh').click(function () {
                queryDeptTree();
            });

            function printTable(noPrintSelector) {
                var time = $('#monthPicker').val()
                time = time.substr(0,7)
                content  = time.replace('-', '年') + '月 ' + deptNameClick + '排班表'
                $("#bootstrap-table").print({
                                                addGlobalStyles: false,
                                                stylesheet: null,
                                                rejectWindow: true,
                                                noPrintSelector: noPrintSelector || ".noPrint",
                                                iframe: true,
                                                append: '',
                                                prepend: '<h2 style="text-align: center">' + (hospitalName) + '值班表</h2>'+ '<h3>' + (content || cc) + '</h3>'
                                            });
                deptNameClick = ''
            }

            function printAllTable() {
                printFlag = 'print'
                queryUserList()
            }

            function printMyTable(noPrintSelector) {

                printFlag = 'my'
                // $.tree.selectByIdName('#tree',deptId,deptName);
                deptNameClick    = deptName
                $('#deptId').val(deptId)
                queryUserList()
            }

            function mergeCells(data, fieldName, colspan, target) {
                //声明一个map计算相同属性值在data对象出现的次数和
                var sortMap = {};
                for (var i = 0; i < data.length; i++) {
                    for (var prop in data[i]) {
                        if (prop == fieldName) {
                            var key = data[i][prop]
                            if (sortMap.hasOwnProperty(key)) {
                                sortMap[key] = sortMap[key] * 1 + 1;
                            } else {
                                sortMap[key] = 1;
                            }
                            break;
                        }
                    }
                }
                for (var prop in sortMap) {
                    console.log(prop, sortMap[prop])
                }
                var index = 0;
                for (var prop in sortMap) {
                    var count = sortMap[prop] * 1;
                    $(target)
                    .bootstrapTable('mergeCells', {index: index, field: fieldName, colspan: colspan, rowspan: count});
                    index += count;
                }
            }
        </script>
    </body>
    <!-- 导入区域 -->
    <script id="importTpl" type="text/template">
        <form enctype="multipart/form-data" class="mt20 mb10">
            <div class="col-xs-offset-1">
                <input type="file" id="file" name="file"/>
                <div class="mt10 pt5">
                    <input type="checkbox" id="updateSupport" name="updateSupport" title="如果登录账户已经存在，更新这条数据。">
                    是否更新已经存在的用户数据
                    &nbsp; <a onclick="$.table.importTemplate()" class="btn btn-default btn-xs"><i
                        class="fa fa-file-excel-o"></i> 下载模板</a>
                </div>
                <font color="red" class="pull-left mt10">
                    提示：仅允许导入“xls”或“xlsx”格式文件！
                </font>
            </div>
        </form>
    </script>
</html>